#include "vertex.h"
#include <QHash>

class VertexPrivate
{
	Q_DISABLE_COPY(VertexPrivate)
public:
	static VertexPrivate *instance(const QString &name);
	~VertexPrivate();
	QString name;
	int degree;
	QAtomicInt refCounter;
private:
	VertexPrivate() : degree(0) { refCounter.ref(); }
	VertexPrivate(const QString &n) : name(n), degree(0) { refCounter.ref(); }
	static QHash<QString, VertexPrivate *> instances;
};

QHash<QString, VertexPrivate *> VertexPrivate::instances;

VertexPrivate *VertexPrivate::instance(const QString &name)
{
	VertexPrivate *p = instances.value(name, 0);
	if (p) {
		p->refCounter.ref();
	} else {
		p = new VertexPrivate(name);
		instances.insert(name, p);
	}
	return p;
}

VertexPrivate::~VertexPrivate()
{
	instances.remove(name);
}

Vertex::Vertex(const QString &name)
	: d(VertexPrivate::instance(name))
{
}

Vertex::Vertex(const Vertex &other)
	: d(other.d)
{
	d->refCounter.ref();
}

Vertex::~Vertex()
{
	if (!d->refCounter.deref())
		delete d;
}

bool Vertex::operator==(const Vertex &other) const
{
	return d == other.d;
}

Vertex &Vertex::operator=(const Vertex &other)
{
	if (!d->refCounter.deref())
		delete d;
	d = other.d;
	d->refCounter.ref();
	return *this;
}

bool Vertex::isNull() const
{
	return d->name.isEmpty();
}

QString Vertex::name() const
{
	return d->name;
}

int Vertex::degree() const
{
	return d->degree;
}

void Vertex::setDegree(int degree)
{
	d->degree = degree;
}

uint qHash(const Vertex &v)
{
	return qHash(v.name());
}
